package com.jastar.android.game.gobang;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.jastar.android.game.gobang.enums.GameMode;
import com.jastar.android.test.R;

import java.text.MessageFormat;

public class GameActivity extends AppCompatActivity {
    public static final String SIGN_IS_AI = "IS_AI";
    public static final String SIGN_IS_MASTER = "IS_MASTER";

    private ChessBoardView chessBoard;
    private TextView tvStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gobang_game);

        chessBoard = findViewById(R.id.chess_board);
        tvStatus = findViewById(R.id.tv_status);

        updateStatus();

        boolean isAI = getIntent().getBooleanExtra(SIGN_IS_AI, false);
        boolean isMaster = getIntent().getBooleanExtra(SIGN_IS_MASTER, false);
        if (isAI) chessBoard.setGameMode(GameMode.VS_AI, isMaster);

        chessBoard.setFocusable(true);
        chessBoard.requestFocus();
        chessBoard.setOnTouchListener(player -> updateStatus());
        chessBoard.setOnGameEndListener(winner -> {
            String msg = MessageFormat.format("游戏结束，{0}方胜利!", (winner == 1) ? "黑" : "白");
            tvStatus.setTextColor(0xFFFF3333);
            tvStatus.setText(msg);
            changeColor(tvStatus, chessBoard.getCurrentPlayer() == 1 ? Color.BLACK : Color.WHITE, 5, 7);
        });

    }

    private void updateStatus() {
        String text = "当前玩家：" + (chessBoard.getCurrentPlayer() == 1 ? "黑方" : "白方");
        tvStatus.setTextColor(chessBoard.getCurrentPlayer() == 1 ? Color.BLACK : Color.WHITE);
        tvStatus.setText(text);
    }

    private void changeColor(TextView textView, int color, int start, int end) {
        SpannableString spannableString = new SpannableString(textView.getText());
        spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvStatus.setText(spannableString);
    }

}